const router = require('koa-router')()
const { models } = require('../../model')
const UserController = require('../../controller/user')
const { ObjectID } = require('mongodb')
const userController = new UserController()

router.use(userController.userFilter())

// 列表
router.get('/list', async function (ctx) {
  const findQuery = {}
  findQuery.createUserId = ctx._user._id
  findQuery.status = {
    $lt: 3
  }
  const docs = await models.MsgChannel
      .find(findQuery)
      .project({})
      .toArray()
  ctx.wrapper.succ(docs)
})

router.post('/create', async function (ctx) {
  if (!ctx._user) return ctx.wrapper.console.error('PERMISSION_ERROR', '未登录')
  const body = ctx.request.body
  const doc = {
    platform: body.platform,
    type: body.type,
    name: body.name,
    webhook: body.webhook,
    accessToken: body.accessToken,
    description: body.description,
    status: 1,
    createUserId: ctx._user._id
  }
  const ret = await models.MsgChannel.insertOne(doc)
  return ctx.wrapper.succ({ _id: ret.insertedId })
})

router.post('/update', async function (ctx) {
  if (!ctx._user) return ctx.wrapper.console.error('PERMISSION_ERROR', '未登录')
  const body = ctx.request.body
  const doc = {
    platform: body.platform,
    type: body.type,
    name: body.name,
    webhook: body.webhook,
    accessToken: body.accessToken,
    description: body.description,
    status: 1,
    updateUserId: ctx._user._id
  }
  const ret = await models.MsgChannel.updateOne({
    _id: ObjectID(body._id)
  }, {
    $set: doc
  }, { multi: false })
  return ctx.wrapper.succ(ret)
})

router.post('/pause', async function (ctx) {
  if (!ctx._user) return ctx.wrapper.console.error('PERMISSION_ERROR', '未登录')
  const ret = await models.MsgChannel.updateOne({
    _id: ObjectID(ctx.request.body.id)
  }, {
    $set: { status: ctx.request.body.status }
  }, { multi: false })
  return ctx.wrapper.succ(ret)
})

router.post('/delete', async function (ctx) {
  if (!ctx._user) return ctx.wrapper.console.error('PERMISSION_ERROR', '未登录')
  const id = ctx.request.body.id
  const ret = await models.MsgChannel.updateOne({
    _id: ObjectID(id)
  }, {
    $set: { status: 3 }
  }, { multi: false })
  return ctx.wrapper.succ(ret)
})

module.exports = router
